﻿# coding:utf-8
import datetime

from selenium import webdriver
import time
import random
import uuid
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
import os, re, io

import numpy as np
import requests
import sys
import traceback, base64
import json, urllib
import hashlib
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import PyChromeDevTools
from selenium.webdriver.support.select import Select

from selenium.webdriver.common.keys import Keys

from bs4 import BeautifulSoup


def Email(port):
    try:
        options = webdriver.ChromeOptions()
        print("开始加载浏览器配置")

        d = DesiredCapabilities.CHROME
        d['loggingPrefs'] = {'performance': 'ALL'}
        options.add_experimental_option("debuggerAddress", "127.0.0.1:" + port)

        browser = webdriver.Chrome(chrome_options=options, desired_capabilities=d)
        chrome = PyChromeDevTools.ChromeInterface(host="127.0.0.1", port=int(port))

        chrome.Network.enable()
        chrome.Page.enable()

        time.sleep(10)
        shifouyishangchuan = 0
        if not browser.find_element(By.XPATH, '//*[@id="paginaCentral"]'):
            print('未找到元素')
            exit()

            # 切换到frame中
        browser.switch_to.frame(browser.find_element(By.XPATH, '//*[@id="paginaCentral"]'))
        print('已切换到frame中')

        # 当天日期
        day_tiannn = datetime.datetime.now()
        ar = (datetime.datetime.now() + datetime.timedelta(hours=-11)).weekday()
        if ar == 5:
            day_tian = (day_tiannn + datetime.timedelta(hours=-11) + datetime.timedelta(days=+2)).strftime('%d/%m/%Y')
        elif ar == 6:
            day_tian = (day_tiannn + datetime.timedelta(hours=-11) + datetime.timedelta(days=+1)).strftime('%d/%m/%Y')
        else:
            day_tian = (day_tiannn + datetime.timedelta(hours=-11)).strftime('%d/%m/%Y')

        week_day_dict = {
            0: '星期一',
            1: '星期二',
            2: '星期三',
            3: '星期四',
            4: '星期五',
            5: '星期六',
            6: '星期天',
        }
        print(week_day_dict[ar])
        print('获取数据巴西日期:{}'.format(day_tian))
        while True:
            try:
                if browser.find_element(By.XPATH, '//*[@id="formFiltroUltimosLancamentos:filtro:divDias1"]/span'):

                    # browser.refresh()
                    browser.find_element(By.XPATH,
                                         '//*[@id="formFiltroUltimosLancamentos:filtro:divDias1"]/span').click()
                    time.sleep(12)

                    html = browser.find_element(By.XPATH,
                                                '//*[@id="formularioUltimosLancamentos:listagem:_id1876"]/div[1]/div/table/tbody[1]').get_attribute(
                        "innerHTML")
                    alllist = []
                    soup = BeautifulSoup(html, features='html.parser')
                    # print(soup.prettify())
                    tr_obj_list = soup.find_all("tr")
                    # print(tr_obj_list)
                    date = ''
                    line = 1
                    for ii in tr_obj_list:
                        line = line + 1
                        # print(ii)
                        tdlist = []
                        td_obj_list = ii.find_all("td")
                        # print(td_obj_list)

                        if td_obj_list[0].text.strip():
                            date = td_obj_list[0].text.strip()

                        if day_tian == date:
                            # 如果是收入 且是当天的数据
                            if td_obj_list[4].text.strip():
                                todo = '{0}_{1}'
                                tdlist.append(date)
                                tdlist.append(todo.format(td_obj_list[3].text.strip(), line))
                                tdlist.append(td_obj_list[1].text.strip())
                                tdlist.append(td_obj_list[3].text.strip())
                                tdlist.append(td_obj_list[4].text.strip())

                                # print("|".join(tdlist))
                                alllist.append("|".join(tdlist))

                    # 如果有下一页

                    if browser.find_elements(By.XPATH, '//*[@id="formularioUltimosLancamentos:listagem:_id2014"]'):
                        print("有下一页数据")
                        browser.find_element(By.XPATH,
                                             '//*[@id="formularioUltimosLancamentos:listagem:_id2014"]').click()
                        time.sleep(6)
                        js = 'window.scorllTo(0,0)'
                        #browser.execute_script(js)
                        # browser.execute_script(js)
                        # //*[@id="formularioUltimosLancamentos:listagem:_id1876"]/div[1]/div/table/tbody[1]
                        htmls = browser.find_element(By.XPATH,
                                                     '//*[@id="formularioUltimosLancamentos:listagem:_id1876"]/div[1]/div/table/tbody[1]').get_attribute(
                            "innerHTML")
                        soups = BeautifulSoup(htmls, features='html.parser')
                        tr_obj_lists = soups.find_all("tr")
                        for iii in tr_obj_lists:
                            line = line + 1
                            # print(ii)
                            tdlist = []
                            td_obj_list = iii.find_all("td")
                            # print(td_obj_list)

                            if td_obj_list[0].text.strip():
                                date = td_obj_list[0].text.strip()

                            if day_tian == date:
                                # 如果是收入 且是当天的数据
                                if td_obj_list[4].text.strip():
                                    todo = '{0}_{1}'
                                    tdlist.append(date)
                                    tdlist.append(todo.format(td_obj_list[3].text.strip(), line))
                                    tdlist.append(td_obj_list[1].text.strip())
                                    tdlist.append(td_obj_list[3].text.strip())
                                    tdlist.append(td_obj_list[4].text.strip())

                                    # print("|".join(tdlist))
                                    alllist.append("|".join(tdlist))

                        print("下一页数据获取完成")
                        print(alllist)

                    else:

                        print("没有下一页数据")
                        print(alllist)

                    headers = {
                        "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
                        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                        "Content-Type": "text/html; charset=UTF-8"}
                    resp = requests.post("https://bra.polymerizations.com/poi/show_code/getbradescodata",
                                         data=json.dumps({"all": alllist, "flag": 1}), headers=headers)
                    # print(resp.text)
                    #day_time = (day_tiannn + datetime.timedelta(hours=-11)).strftime('%Y-%m-%d %H:%M:%S')
                    #output = """操作时间：{} \n数据：{} \n"""
                    #save_txt(output.format(day_time, json.dumps({"all": alllist, "flag": 1})))
                    time.sleep(40)  # 刷新时间

            except Exception as e:
                print(e)

            time.sleep(3)

    except Exception as e:
        # browser.quit()

        print(traceback.print_exc())
        print(str(e))
        return False

    # browser.quit()


# 保存到文本中
def save_txt(data):
    name = '{0}.txt'
    day_tiannn = datetime.datetime.now()
    day = (day_tiannn + datetime.timedelta(hours=-11)).strftime('%Y-%m-%d')
    with open(name.format(day), 'a', encoding='utf-8') as f:
        f.write(data)


port = ""
with open(sys.path[0].replace("\\", "/") + "/DevToolsActivePort", "r")as f:
    data = f.read()
    print(data)
    port = data.split("\n")[0]
Email(port=port)
# while True:
#     Email(port=port)
#     time.sleep(20)
